package com.yanqu.road.server.channelserver.cmd.voucher;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.entity.activity.cookboy.CookBoyFood;
import com.yanqu.road.entity.voucher.eVoucherType;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.voucher.VoucherProto;
import com.yanqu.road.server.channelserver.cmd.ChannelCommand;
import com.yanqu.road.server.channelserver.logic.ChannelMessageHelper;
import com.yanqu.road.server.channelserver.manager.voucher.ChannelVoucherMgr;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.protocol.ChannelProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Cmd(code = ChannelProtocol.N_CROSS_VOUCHER_USE, desc = "使用代金券")
public class ChannelVoucherUseCmd extends ChannelCommand {

    private int channelId;

    private long serverId;

    private long userId;

    private int type;

    private String cost;

    private Map<Integer, List<BigInteger>> priceParamMap = new HashMap<>();

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        VoucherProto.ChannelVoucherUseReqMsg reqMsg = VoucherProto.ChannelVoucherUseReqMsg.parseFrom(packet.getBytes());
        channelId = reqMsg.getChannelId();
        serverId = reqMsg.getServerId();
        userId = packet.getPlayerId();
        type = reqMsg.getType();
        cost = reqMsg.getCost();
        priceParamMap = JSON.parseObject(reqMsg.getPriceParam(), new TypeReference<Map<Integer, List<BigInteger>>>() {
        });
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        eVoucherType eVoucherType = com.yanqu.road.entity.voucher.eVoucherType.valueOf(type);
        if (eVoucherType == null) {
            // 未知类型
            ret = GameErrorCode.E_ERROR_PARAMETER;
            return;
        }
        ret = ChannelVoucherMgr.voucherUse(channelId, serverId, userId, type, cost, priceParamMap);
    }

    @Override
    public void sendData() {
        if (ret != 0) {
            VoucherProto.ChannelVoucherUseRespMsg.Builder respMsg = VoucherProto.ChannelVoucherUseRespMsg.newBuilder();
            respMsg.setRet(ret);
            respMsg.setPreCost(cost);
            ChannelMessageHelper.sendGamePacket(Protocol.S_VOUCHER_USE_FROM_CROSS, respMsg, channelId, serverId, userId);
        }
    }
}
